# -*- coding: utf-8 -*-
from flask import Blueprint, jsonify, request
from flasgger import swag_from
from werkzeug.utils import secure_filename
from ..tool.summer.link import summarize_webpage
from ..tool.summer.document import summarize_document


bp = Blueprint('summarizefn', __name__)
@bp.route('/summarize/link', methods=['POST'])
@swag_from({
    'parameters': [
        {
            'name': 'messages',
            'in': 'body',
            'required': True,
            'schema': {
                'type': 'object',
                'properties': {
                    'model': {
                        'type': 'string',
                        'example': 'llama3'
                    },
                    'messages': {
                        'type': 'array',
                        'items': {
                            'type': 'object',
                            'properties': {
                                'role': {
                                    'type': 'string',
                                    'example': 'link'
                                },
                                'content': {
                                    'type': 'string',
                                    'example': 'https://mp.weixin.qq.com/s/yc9QJGeu-9zuOdGdX4Lk3g'
                                }
                            }
                        },
                        'example': [
                            {"role": "link", "content": "https://mp.weixin.qq.com/s/yc9QJGeu-9zuOdGdX4Lk3g"}
                        ]
                    }
                }
            }
        },
        {
            'name': 'file',
            'in': 'formData',
            'type': 'file',
            'required': False,
            'description': '上传的文件'
        }
    ],
    'responses': {
        200: {
            'description': 'Successful Response',
            'examples': {
                'application/json': {
                    "choices": [
                        {
                            "finish_reason": "stop",
                            "index": 0,
                            "message": {
                                "content": "你好！有什么我可以帮助你的吗？",
                                "role": "assistant",
                                "tool_calls": ""
                            }
                        }
                    ],
                    "created": 1724298149,
                    "id": "chatcmpl-40da0c2bbe364987b33a182326229ac4",
                    "model": "llama3",
                    "object": "chat.completion",
                    "usage": {
                        "completion_tokens": 11,
                        "prompt_tokens": 13,
                        "total_tokens": 24
                    }
                }
            }
        }
    }
})
def summarize():
    """
    内容总结 - 链接和文件总结内容
    ---
    tags:
      - 内容总结功能
    """
    try:
        data = request.get_json()
        print(data)

        # 检查请求数据是否存在并符合预期结构
        if not data or 'messages' not in data or not isinstance(data['messages'], list):
            return jsonify({"error": "Invalid input format"}), 400

        content = data['messages'][0].get('content')
        role = data['messages'][0].get('role')

        # 检查 role 和 content 是否存在
        if not content or not role:
            return jsonify({"error": "Missing role or content in request data"}), 400

        # 处理不同的 role
        if role == 'link':
            summary = summarize_webpage(content)  # 假设这是一个有效的函数
            print(summary)
            return jsonify({"summary": summary}), 200
        elif role == 'file':
            # 处理文件上传
            if 'file' not in request.files:
                return jsonify({"error": "No file part in the request"}), 400

            file = request.files['file']
            if file.filename == '':
                return jsonify({"error": "No file selected for uploading"}), 400

            filename = secure_filename(file.filename)
            summary = summarize_document(file)
            if summary:
                return jsonify({"summary": summary}), 200
            else:
                return jsonify({"error": "Failed to summarize the document"}), 500
        else:
            return jsonify({"error": "Unsupported role type"}), 400

    except Exception as e:
        print(f"Error during summarization: {e}")
        return jsonify({"error": "Internal server error"}), 500
